package server

import (
	"context"
	categoryPb "glmall-product/api/category"
	"glmall-product/internal/conf"
	"glmall-product/internal/service"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
)

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, greeter *service.GreeterService, category *service.CategoryService, logger log.Logger) *runtime.ServeMux {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	gatewayMux := runtime.NewServeMux()
	opt := []grpc.DialOption{grpc.WithInsecure()}

	if err := categoryPb.RegisterCategoryHandlerFromEndpoint(context.Background(), gatewayMux, c.Http.Addr, opt); err != nil {
		log.Error(err)
	}
	return gatewayMux
}
